/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.app.course.exercise.record.web;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.common.collect.Lists;
import com.jeesite.modules.app.util.answer.AnswerUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jeesite.common.mapper.JsonMapper;
import com.jeesite.modules.app.course.exercise.record.entity.TcourseExerciseRecord;
import com.jeesite.modules.app.course.exercise.record.service.TcourseExerciseRecordService;
import com.jeesite.modules.conf.AppController;
import com.jeesite.modules.conf.MessageCode;
import com.jeesite.modules.conf.RedisUtils;
import com.jeesite.modules.zx.course.entity.Tcourses;
import com.jeesite.modules.zx.course.service.TcoursesService;

/**
 * 课程练习记录Controller
 * @author zpp
 * @version 2020-02-17
 */
@Controller
@RequestMapping(value = "/app/course/exercise/record/")
public class TcourseExerciseRecordController{

	@Autowired
	private TcourseExerciseRecordService tcourseExerciseRecordService;
	@Autowired
	private TcoursesService tcoursesService;
	@Autowired
	private RedisUtils redisUtils;
	
	
	
	
	@RequestMapping(value = "findList")
	public void findList(TcourseExerciseRecord entity,HttpServletRequest request,HttpServletResponse response) {
		String userId = entity.getUserId();
		if(StringUtils.isBlank(userId)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "用户标识");
			return;
		}
		List<TcourseExerciseRecord> findList = tcourseExerciseRecordService.findList(entity);
		JSONArray jsonArr=JSONObject.parseArray(JsonMapper.toJson(findList));
		AppController.renderSuccessObject(response, jsonArr, MessageCode.SUCCESS_ACK);
	}

	@RequestMapping(value = "findListNew")
	public void findListNew(TcourseExerciseRecord entity,HttpServletRequest request,HttpServletResponse response) {
		String userId = entity.getUserId();
		if(StringUtils.isBlank(userId)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "用户标识");
			return;
		}
		List<TcourseExerciseRecord> findList = tcourseExerciseRecordService.findList(entity);

		if (findList.size()>0){
			findList.forEach(item->{
				Tcourses tcourse=new Tcourses();
				tcourse.setParentCode(item.getQuestionId());
				List<Tcourses> optionList = tcoursesService.findList(tcourse);
				String answerId = item.getAnswerId()==null?"":item.getAnswerId();
				List<String>  answerOptionIds = optionList.stream().filter(e->e.getAnswer()!=null&&e.getAnswer()==1).map(e->e.getId()).collect(Collectors.toList());
				boolean flag = correctJudgment(answerId,answerOptionIds);
				item.setFlag(flag);
			});
		}
		JSONArray jsonArr=JSONObject.parseArray(JsonMapper.toJson(findList));
		AppController.renderSuccessObject(response, jsonArr, MessageCode.SUCCESS_ACK);
	}


	/**
	 *  判断选择的答案是否和正确
	 * @param answerId 选择的答案
	 * @param answerOptionIds 正确答案
	 * @return
	 */
	private boolean correctJudgment(String answerId,List<String>  answerOptionIds){
		//单选题
		boolean flag = true;
		if (answerOptionIds.size()==1){
			if (!answerOptionIds.get(0).equals(answerId)){
				flag = false;
			}
		}
		//多选题
		List<String> answerIds = Lists.newArrayList(answerId.split(","));
		if (answerIds.size() == answerOptionIds.size()){
		    for(String answer:answerIds){
		    	if (!answerOptionIds.contains(answer)){
		    		flag = false;
				}
			}
		}else{
			flag = false;
		}
		return flag;
	}

	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("app:course:exercise:record:tcourseExerciseRecord:view")
	@RequestMapping(value = "form")
	public String form(TcourseExerciseRecord tcourseExerciseRecord, Model model) {
		model.addAttribute("tcourseExerciseRecord", tcourseExerciseRecord);
		return "modules/app/course/exercise/record/tcourseExerciseRecordForm";
	}
	
	/**
	 * 保存课程练习记录  多选
	 */
	@RequestMapping(value = "savemul")
	public void savemul(TcourseExerciseRecord entity,HttpServletRequest request,HttpServletResponse response) {
		String userId = entity.getUserId();
		if(StringUtils.isBlank(userId)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "用户标识");
			return;
		}
		String courseId=entity.getCourseId();
		if(StringUtils.isBlank(courseId)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "课程标识");
			return;
		}
		String answerId=entity.getAnswerId();
		if(StringUtils.isBlank(answerId)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "答案标识");
			return;
		}
		String[] split = answerId.split(",");
		List<String> list=new ArrayList<String>();
		for(String id:split){
			list.add(id);
		}
		String questionId=entity.getQuestionId();
		if(StringUtils.isBlank(questionId)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "问题标识");
			return;
		}
		TcourseExerciseRecord ter=new TcourseExerciseRecord();
		ter.setCourseId(courseId);
		ter.setQuestionId(questionId);
		ter.setUserId(userId);
		List<TcourseExerciseRecord> findList = tcourseExerciseRecordService.findList(ter);
		String id="";
		if(findList!=null&&findList.size()>0){
			id=findList.get(0).getId();
		}
		Tcourses tcourses = new Tcourses();
		tcourses.setParentCode(questionId);
		tcourses.setAnswer(1);
		Object redisList=null;
		try {
			redisList = redisUtils.get(questionId+"answer");
		} catch (Exception e) {
			e.printStackTrace();
		}
		List<Tcourses> findList2=new ArrayList<Tcourses>();
		if(redisList!=null) {
			findList2=JSONObject.parseArray(JsonMapper.toJson(redisList), Tcourses.class);
		}else {
		    findList2 = tcoursesService.findList(tcourses);
		    JSONArray parseArray = JSONObject.parseArray(JsonMapper.toJson(findList2));
		    try {
				boolean set = redisUtils.set(questionId+"answer", parseArray, 1000*60*5);
				if(!set) {
					System.out.println("redis Save error");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		int a=findList2.size();
		int b=list.size();
		//先判断长度是否相等
		if(a==b){
			boolean addScor=true;
			for(Tcourses tc:findList2){
				String tcId = tc.getId();
				if(!list.contains(tcId)){
					addScor=false;
				}
			}
			if(addScor){
				Tcourses answerObj = tcoursesService.get(questionId);
				entity.setScore(answerObj.getScore());
			}else{
				entity.setScore(new BigDecimal(0));
			}
		}else{
			entity.setScore(new BigDecimal(0));
		}
		
		if(StringUtils.isNotBlank(id)){
			entity.setId(id);
			tcourseExerciseRecordService.update(entity);
		}else{
			tcourseExerciseRecordService.save(entity);
		}
		JSONObject parseObject = JSONObject.parseObject(JsonMapper.toJson(entity));
		AppController.renderSuccessObject(response, parseObject, MessageCode.SUCCESS_ACK);
		
	}
	/**
	 * 单选保存
	 * @param entity
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "save")
	public void save(TcourseExerciseRecord entity,HttpServletRequest request,HttpServletResponse response) {
		String userId = entity.getUserId();
		if(StringUtils.isBlank(userId)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "用户标识");
			return;
		}
		String courseId=entity.getCourseId();
		if(StringUtils.isBlank(courseId)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "课程标识");
			return;
		}
		String answerId=entity.getAnswerId();
		if(StringUtils.isBlank(answerId)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "答案标识");
			return;
		}
		String questionId=entity.getQuestionId();
		if(StringUtils.isBlank(questionId)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "问题标识");
			return;
		}
		String courseHourseId=entity.getCourseHourseId();
		if(StringUtils.isBlank(courseHourseId)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "课时标识");
			return;
		}
		TcourseExerciseRecord ter=new TcourseExerciseRecord();
		ter.setCourseId(courseId);
		ter.setCourseHourseId(courseHourseId);
		ter.setQuestionId(questionId);
		ter.setUserId(userId);
		List<TcourseExerciseRecord> findList = tcourseExerciseRecordService.findList(ter);
		String id="";
		if(findList!=null&&findList.size()>0){
			id=findList.get(0).getId();
		}
		
		
		Tcourses tcourses =tcoursesService.get(answerId);
		Integer answer = tcourses.getAnswer();
		if(answer!=null&&answer==1){
			Tcourses question = tcoursesService.get(questionId);
			BigDecimal score = question.getScore();
			if(score==null){
				score=new BigDecimal(0.0);
			}
			entity.setScore(score);
		}else{
			entity.setScore(new BigDecimal(0.0));
		}
		if(StringUtils.isNotBlank(id)){
			entity.setId(id);
			tcourseExerciseRecordService.update(entity);
		}else{
			tcourseExerciseRecordService.save(entity);
		}
		JSONObject parseObject = JSONObject.parseObject(JsonMapper.toJson(entity));
		AppController.renderSuccessObject(response, parseObject, MessageCode.SUCCESS_ACK);
	}
	/**
	 * 停用课程练习记录
	 */
	@RequiresPermissions("app:course:exercise:record:tcourseExerciseRecord:edit")
	@RequestMapping(value = "disable")
	@ResponseBody
	public String disable(TcourseExerciseRecord tcourseExerciseRecord) {
		tcourseExerciseRecord.setStatus(TcourseExerciseRecord.STATUS_DISABLE);
		tcourseExerciseRecordService.updateStatus(tcourseExerciseRecord);
		return "停用课程练习记录成功";
	}
	
	/**
	 * 启用课程练习记录
	 */
	@RequiresPermissions("app:course:exercise:record:tcourseExerciseRecord:edit")
	@RequestMapping(value = "enable")
	@ResponseBody
	public String enable(TcourseExerciseRecord tcourseExerciseRecord) {
		tcourseExerciseRecord.setStatus(TcourseExerciseRecord.STATUS_NORMAL);
		tcourseExerciseRecordService.updateStatus(tcourseExerciseRecord);
		return "启用课程练习记录成功";
	}
	
	/**
	 * 删除课程练习记录
	 */
	@RequiresPermissions("app:course:exercise:record:tcourseExerciseRecord:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(TcourseExerciseRecord tcourseExerciseRecord) {
		tcourseExerciseRecordService.delete(tcourseExerciseRecord);
		return "删除课程练习记录成功！";
	}
	
}